package com.lib.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lib.common.properties.JwtProperties;
import com.lib.common.properties.WeChatProperties;
import com.lib.common.utils.HttpClientUtil;
import com.lib.mapper.UserLoginMapper;
import com.lib.pojo.DTO.UserLoginDTO;
import com.lib.pojo.entity.User;
import com.lib.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
public class UserLoginServiceImpl implements UserLoginService  {
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    //1:用户登录
    @Override
    public User WxLogin(UserLoginDTO userLoginDTO)  {
        //1：调用微信接口获取当前用户的openId
        String openid = getOpenid(userLoginDTO.getCode());
        //2：判断是否获取到openId，若为空则报异常
        if (openid == null){
            throw new RuntimeException("没有获取到openId");
        }
        //3：查询数据库里面是否有这个用户openId 查询是否是新用户
        User user = userLoginMapper.getByOpenid(openid);
        //4：若是新用户就完成注册 没有的话，就添加到数据库
        if (user == null){
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userLoginMapper.insert(user);
        }
        //返回用户对象
        return user;
    }
    //调用微信接口服务获取当前用户的openId
    private String getOpenid(String code) {
        //调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String s = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(s);
        return jsonObject.getString("openid");
    }
}
